package com.gitee.wsl.ext.array

//fun ByteArray.padStart(length: Int, byte: Byte = 0x00): ByteArray {
//    if (size % length == 0) return this
//    val padCount = length - size % length
//    val bytes = ByteArray(size + padCount)
//    repeat(padCount) { bytes[it] = byte }
//    copyInto(bytes, padCount)
//    return bytes
//}

fun ByteArray.padStart(toSize: Int, pad: Byte = 0x00) = when {
    this.size < toSize -> (ByteArray(toSize - this.size) { pad } + this)
    else -> this
}

fun ByteArray.padStart(toSize: UInt, pad: Byte = 0x00) =
    padStart(toSize.toInt(), pad)


@OptIn(ExperimentalUnsignedTypes::class)
fun UByteArray.getPadded(length: Int): UByteArray {
    val paddingLength = length - this.size
    if (paddingLength < 0) {
        throw Error("Length smaller than this.length")
    }
    val padding = UByteArray(paddingLength) { 0u }
    return padding + this
}


/**
 * @param length new array size
 * @return Value in `a` plus `length` appended 0 bytes
 */
fun ByteArray.padTail(length: Int): ByteArray {
    val padding = ByteArray(length)
    for (i in 0..<length) {
        padding[i] = 0
    }
    return this + padding
}

